/**
 * 462. 最少移动次数使数组元素相等 II462. 最少移动次数使数组元素相等 II
 * https://leetcode.cn/problems/minimum-moves-to-equal-array-elements-ii/
 */

/**
 * @param {number[]} nums
 * @return {number}
 */
function minMoves2(nums) {
  nums.sort((a, b) => a - b);
  const target = nums[Math.floor(nums.length / 2)];
  let step = 0;
  for (let i = 0; i < nums.length; i += 1) {
    step += Math.abs(nums[i] - target);
  }
  return step;
}

console.log(minMoves2([1, 2, 3]) === 2);
console.log(minMoves2([1, 10, 2, 9]) === 16);
console.log(minMoves2([1, 0, 0, 8, 6]) === 14);
